﻿<%@ WebHandler Language="C#" Class="getTypes" %>

using System;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Security;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class getTypes : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //指定回送数据的类型
        context.Response.ContentType = "application/json";
        string tid = context.Request["tid"];

        //准备回送的字符串
        string outstr = "";

        //执行写入操作
        outstr = doSelect(tid);


        //回送结果
        context.Response.Write(outstr);
    }

    public string doSelect(string tid)
    {
        string sql = "";
        // 获取全部类别
        if (tid == null)
        {
            //执行查询操作，并获得返回的行数
            sql = "select id, tname from types";
        }
        // 获取指定类别
        else
        {
            //执行查询操作，并获得返回的行数
            sql = "select id, tname from types where id = '" + tid + "'";

        }
        DataSet ds = DBHelper.sqlMethod(sql);
        int i = ds.Tables[0].Rows.Count;
        StringBuilder Builder = new StringBuilder();
        Builder.Append("{");
        Builder.Append("\"r\":" + i + "");

        if (i > 0)
        {
            List<Tags> list = new List<Tags>();

            for (int j = 0; j < i; j++)
            {
                Tags temp = new Tags(int.Parse(ds.Tables[0].Rows[j][0].ToString()), ds.Tables[0].Rows[j][1].ToString());
                list.Add(temp);
            }

            string json = new JavaScriptSerializer().Serialize(list);//这个很关键，否则error 

            Builder.Append(",\"data\":");
            Builder.Append(json);
        }

        Builder.Append("}");
        return Builder.ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}